package com.j2data.spike.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.j2data.spike.exception.GlobalException;
import com.j2data.spike.mapper.OrderMapper;
import com.j2data.spike.mapper.SpikeGoodsMapper;
import com.j2data.spike.mapper.SpikeOrderMapper;
import com.j2data.spike.pojo.Order;
import com.j2data.spike.pojo.SpikeGoods;
import com.j2data.spike.pojo.SpikeOrder;
import com.j2data.spike.pojo.User;
import com.j2data.spike.service.IGoodsService;
import com.j2data.spike.service.IOrderService;
import com.j2data.spike.service.ISpikeGoodsService;
import com.j2data.spike.service.ISpikeOrderService;
import com.j2data.spike.utils.JsonUtil;
import com.j2data.spike.utils.MD5Util;
import com.j2data.spike.utils.UUIDUtil;
import com.j2data.spike.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.util.StringUtils;

import java.rmi.server.UID;
import java.util.Date;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author j2data
 * @since 2022-07-05
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ISpikeGoodsService spikeGoodsService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SpikeOrderMapper spikeOrderMapper;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private ISpikeOrderService spikeOrderService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 秒杀
     *
     * @param user
     * @param goodsVo
     * @return
     */
    @Override
    @Transactional
    public Order spike(User user, GoodsVo goodsVo) {
        ValueOperations valueOperations = redisTemplate.opsForValue();
        //秒杀商品减库存
        SpikeGoods spikeGoods = spikeGoodsService.getOne(new QueryWrapper<SpikeGoods>()
                .eq("goods_id", goodsVo.getId()));
        spikeGoods.setStockCount(spikeGoods.getStockCount() - 1);
        boolean result = spikeGoodsService.update(new UpdateWrapper<SpikeGoods>()
                .setSql("stock_count = " + "stock_count-1")
                .eq("goods_id", goodsVo.getId())
                .gt("stock_count", 0));
        if (spikeGoods.getStockCount() < 1) {
            //判断是否还有库存
            valueOperations.set("isStockEmpty:" + goodsVo.getId(), "0");
            return null;
        }

        //生成订单
        Order order = new Order();
        order.setUserId(user.getId());
        order.setGoodsId(goodsVo.getId());
        order.setDeliveryAddrId(0L);
        order.setGoodsName(goodsVo.getGoodsName());
        order.setGoodsCount(1);
        order.setGoodsPrice(spikeGoods.getSpikePrice());
        order.setOrderChannel(1);
        order.setStatus(0);
        order.setCreateDate(new Date());
        orderMapper.insert(order);

        //生成秒杀订单
        SpikeOrder spikeOrder = new SpikeOrder();
        spikeOrder.setUserId(user.getId());
        spikeOrder.setOrderId(order.getId());
        spikeOrder.setGoodsId(goodsVo.getId());
        spikeOrderService.save(spikeOrder);
        valueOperations.set("order:" + user.getId() + ":" + goodsVo.getId()
                , spikeOrder);
        return order;

    }

    /**
     * 订单详情
     *
     * @param orderId
     * @return
     */
    @Override
    public OrderDetailVo detail(Long orderId) {
        if (orderId == null) {
            throw new GlobalException(RespBeanEnum.ORDER_NOT_EXIST);
        }
        SpikeOrder spikeOrder = spikeOrderMapper.selectById(orderId);
        Order order = orderMapper.selectById(spikeOrder.getOrderId());
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(order.getGoodsId());
        OrderDetailVo orderDetailVo = new OrderDetailVo();

        orderDetailVo.setOrder(order);
        orderDetailVo.setGoodsVo(goodsVo);

        return orderDetailVo;
    }

    /**
     * 获取秒杀地址
     *
     * @param user
     * @param goodsId
     * @return
     */
    @Override
    public String createPath(User user, Long goodsId) {
        String str = MD5Util.md5(UUIDUtil.uuid() + "123456");
        redisTemplate.opsForValue().set("spikePath:" + user.getId() + ":" + goodsId, str, 60, TimeUnit.SECONDS);
        return str;
    }

    /**
     * 校验秒杀地址
     *
     * @param user
     * @param goodsId
     * @param path
     * @return
     */
    @Override
    public Boolean checkPath(User user, Long goodsId, String path) {
        if (user == null || goodsId < 0 || StringUtils.isEmpty(path)) {
            return false;
        }
        String redisPath = (String) redisTemplate.opsForValue().get("spikePath:" + user.getId() + ":" + goodsId);
        return path.equals(redisPath);
    }

    /**
     * 校验验证码
     *
     * @param user
     * @param goodsId
     * @param captcha
     * @return
     */
    @Override
    public Boolean checkCaptcha(User user, Long goodsId, String captcha) {
        if (StringUtils.isEmpty(captcha) || user == null || goodsId < 0) {
            return false;
        }
        String redisCaptcha = (String) redisTemplate.opsForValue().get("captcha:"+user.getId() + ":"+goodsId);
        return captcha.equals(redisCaptcha);
    }
}
